//
// 2.10.1 select
// select() loop, need to initialize timeva and fds every loop.
//
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

#define TIMEOUT (5)
#define BUF_LEN (1024)
#define TRUE (1)
#define FALSE (0)

int main(int argc, char** argv)
{
    printf("Test select loop, read data from STDIN and print it.\n");
    printf("enter \"quit\" to quit loop\n");
    struct timeval tv;
    fd_set readfds;
    int ret;
    int bQuit = FALSE;

    while(!bQuit)
    {
        // need to reinit the timeval struct and fd collection every loop;
        tv.tv_sec = TIMEOUT;
        tv.tv_usec = 0;
        //
        FD_ZERO(&readfds);
        FD_SET(STDIN_FILENO, &readfds);

        ret = select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv);
        if (-1 == ret)
        {
            perror("select");
            break;
        }
        else if (!ret)
        {
            // timeout
            printf("timeout with %d seconds.\n", TIMEOUT);
            continue;
        }
        else
        {
            if (FD_ISSET(STDIN_FILENO, &readfds))
            {
                char buf[BUF_LEN + 1] = {0};
                int len;
                len = read(STDIN_FILENO, buf, BUF_LEN);
                if (-1 == len)
                {
                    perror("read stdin");
                    break;
                }
                if (len)
                {
                    buf[len] = 0;
                    printf("read: %s\n", buf);
                    if (0 == strcasecmp(buf, "quit\n"))
                    {
                        printf("over\n");
                        break;
                    }
                    else
                        continue;
                }
            }

            fprintf(stderr, "logic error, cannot be here.\n");
            return 1;
        }
    }
    return 0;
}

